<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>桥接模式</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body,
    html {
      height: 100%;
    }

    div {
      width: 200px;
      height: 200px;
      border: 1px solid gray;
      float: left;
      margin: 20px;
      text-align: center;
      /* line-height: 200px; */
      /* background-color: #fff; */
    }
  </style>
</head>

<body>
  <div id="div1">div1, green+red, black+ white</div>
  <div id="div2">div2, gray + blue, pink + black</div>
  <div id="div3">div3, orange + black, green + white</div>
  <div id="div4">div4, blue + gray, green + yellow</div>
  <script>
    //   要求：给上面4个DIV都点击移入和移出事件：
    //  移入时，每个DIV显示不同的背景色和文字颜色。移出时，每个DIV显示不同的背景色和文字颜色。
    //   let div1 = document.querySelector("#div1");
    //   let div2 = document.querySelector("#div2");
    //   let div3 = document.querySelector("#div3");
    //   let div4 = document.querySelector("#div4");
    /* 
    // 传统写法，事件绑定或修改CSS是写在一起的。
     div1.onmouseenter=function(){
       this.style.backgroundColor = '';
       this.style.color = ''
     }
     dvi1.onmouseout=function(){
       this.style.backgroundColor = '';
       this.style.color = ''
     }
      */

    // 桥接模式：抽取相同的代码，单独写成一个函数，把业务抽取出来，让函数和事件中的this解耦。
    const changeStyle = (dom, bgColor, textColor) => {
      dom.style.backgroundColor = bgColor;
      dom.style.color = textColor;
    }

    let styleArr = [
      ["green", "red", "black", "white"], // [bgcolor, textcolor, bgcolor, textcolor, ]
      ["gray", "blue", "pink", "black"],
      ["orange", "black", "green", "white"],
      ["blue", "gray", "green", "yellow"],
    ];

    // 事件的绑定：
    let divList = document.querySelectorAll('div')
    divList.forEach((el, index) => {
      let arr = styleArr[index]
      el.onmouseenter = function () {
        changeStyle(this, arr[0], arr[1])
        // this.style.backgroundColor=arr[0]
      }
      el.onmouseout = function () {
        changeStyle(this, arr[2], arr[3])
      }
    })
  </script>
</body>

</html>